package com.cks.wfman;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

public class WFMAdmin {
	SessionFactory session;
	public WFMAdmin (){
		session = HibernateUtil.getSessionFactory();
	}
	
	public long createUser (String uName) {
		Session sess = session.getCurrentSession();
		Transaction tx = sess.beginTransaction();
		WFMUser wUser = new WFMUser();
		wUser.setUserName(uName);
		sess.save(wUser);
		tx.commit();
		long id=wUser.userId;
		return id;
	}
	
	public WFMUser getUser (long userId){
		Session sess = session.getCurrentSession();
		sess.beginTransaction();
		WFMUser wUser = (WFMUser)sess.get(WFMUser.class,userId);
		sess.getTransaction().commit();
		return wUser;
	}
	
	public void deleteUser (long userId) {
		WFMUser wUser = getUser (userId);
		Session sess = session.getCurrentSession();
		sess.beginTransaction();
		sess.delete(wUser);
		sess.getTransaction().commit();
	}
	
	public WFMUser getByUserName (String uName){
		Session sess = session.getCurrentSession();
		sess.beginTransaction();
		Criteria criteria = sess.createCriteria(WFMUser.class)
			.add(Restrictions.eq("userName",uName));
		
		return ((WFMUser)criteria.uniqueResult());
	}
}
